import { defineStore } from 'pinia'

export const useGameStore = defineStore('game', {
    state: () => ({
        // 确保使用响应式对象
        opponents: {
            player1: { id: '', username: '', photo: '' },
            player2: { id: '', username: '', photo: '' },
        },
        status: 'matching',
        socket: null,
        gameObject: null,
        a_id: 0,
        b_id: 0,
        c_id:0,
        loser: 'none',
        resultDetermined: false, // 标识是否已经确定游戏结果
        showInvitation: true, // 控制是否显示游戏邀请弹窗
    }),
    actions: {
        // 使用深层更新方式
        updateOpponents(newOpponents) {
            this.$patch({
                opponents: newOpponents,
            })
        },
        updateStatus(status) {
            this.status = status
        },
        updateSocket(socket) {
            this.socket = socket
        },
        updateGameObject(gameObject) {
            this.gameObject = gameObject
        },
        updateGame(game) { 
            this.$patch({
                a_id: game.a_id,
                b_id: game.b_id,
                c_id: game.c_id,
            })
        },
        // 更新胜负结果，增加防止重复设置的逻辑
        updateLoser(loser) {
            // 如果已经确定了结果且不是重置操作，则忽略后续更新
            if (this.resultDetermined && loser !== 'none') {
                console.log('已经确定了游戏结果，忽略新的结果:', loser)
                return
            }

            if (loser === 'none') {
                // 重置游戏时
                this.resultDetermined = false
            } else {
                // 设置结果时
                this.resultDetermined = true
            }

            this.loser = loser
        },
        // 处理玩家死亡事件 - 只处理从后端接收到的死亡事件
        handlePlayerDeath(playerId) {
            // 安全检查：验证参数
            if (!playerId) {
                console.error('处理玩家死亡事件失败: 无效的玩家ID')
                return
            }
            
            // 检查游戏状态
            if (this.loser !== 'none') {
                return
            }

            // 本地标记玩家为死亡状态，确保UI及时更新
            if (this.gameObject && this.gameObject.players) {
                for (const player of this.gameObject.players) {
                    // 使用info.userId而不是id或uuid
                    if (player.info && player.info.userId == playerId) {
                        if (player.info.hp > 0) {
                            player.info.hp = 0
                            player.is_dead = true
                            
                            // 如果存在set_death方法，调用它
                            if (typeof player.set_death === 'function') {
                                try {
                                    player.set_death()
                                } catch(e) {
                                    console.error(`调用set_death方法失败:`, e)
                                }
                            }
                        }
                        break
                    }
                }
            }
        },
        resetGame() {
            try {
                // 清理所有游戏对象
                const oldGameObject = this.gameObject;
                let GameObject = null;
                
                if (oldGameObject) {
                    // 尝试获取GameObject类引用
                    try {
                        GameObject = oldGameObject.constructor.constructor;
                        if (typeof GameObject.clearAll === 'function') {
                            GameObject.clearAll();
                        }
                    } catch (e) {
                        console.warn('获取GameObject类引用失败:', e);
                    }
                    
                    // 在移除引用前，设置销毁标记防止resize等方法继续使用
                    if (oldGameObject._destroyed !== true) {
                        oldGameObject._destroyed = true;
                    }
                }
                
                // 断开引用
                this.gameObject = null;
                
                // 重置状态
                this.$patch({
                    status: 'matching',
                    opponents: {
                        player1: { id: '', username: '', photo: '' },
                        player2: { id: '', username: '', photo: '' },
                    },
                    a_id: 0,
                    b_id: 0,
                    c_id: 0,
                    loser: 'none',
                    resultDetermined: false,
                    showInvitation: true, // 确保显示邀请窗口
                });
            } catch (error) {
                console.error('游戏重置过程中发生错误:', error);
                // 即使出错，也尝试重置基本状态
                this.$patch({
                    status: 'matching',
                    gameObject: null,
                    loser: 'none',
                });
            }
        },
    },
})
